package com.ews.onlineexchange.service;

import java.text.NumberFormat;
import java.util.Calendar;

import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
import javax.persistence.Query;

import com.ews.onlineexchange.model.Complaint;

@Named
@ConversationScoped
public class ComplaintHome extends EntityHome<Complaint, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	static NumberFormat nf;
	static {
		nf = NumberFormat.getInstance();
		nf.setMaximumFractionDigits(0);
		nf.setMinimumIntegerDigits(3);
		nf.setGroupingUsed(false);
	}

	@Override
	public String save() {
		if (!isManaged()) {
			String seqNo = findNextSeqNo();
			getInstance().setSeqNo(seqNo);
		}
		return super.save();
	}

	private static final String FIND_NEXT_INT_EQL = ""
			+ "	SELECT		COUNT(c.id) "
			+ "	FROM		Complaint c "
			+ "	WHERE		c.seqNo LIKE :seqNoPrefix";
	private String findNextSeqNo() {
		StringBuilder seqNoPrefix = new StringBuilder();
		Calendar cal = Calendar.getInstance();
		seqNoPrefix	.append(cal.get(Calendar.YEAR))
					.append(cal.get(Calendar.MONTH) + 1)
					.append(cal.get(Calendar.DAY_OF_MONTH));
		
		Query query = getEntityManager().createQuery(FIND_NEXT_INT_EQL);
		query.setParameter("seqNoPrefix", seqNoPrefix.toString().concat("%"));
		Long count = (Long) query.getSingleResult();
		return seqNoPrefix.append(nf.format(count + 1)).toString();
	}	

}
